package com.yl.openstore

import android.Manifest
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Toast
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_main.*
import java.io.BufferedReader
import java.io.File
import java.io.InputStream
import java.io.InputStreamReader
import java.util.regex.Pattern


class MainActivity : AppCompatActivity() {
    var packageNamea = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setPermission()
    }

    fun dian(view: View) {
        goToMarket(this, packageNamea)
        finish()
    }

    fun goToMarket(context: Context, packageName: String) {
        val uri = Uri.parse("market://details?id=$packageName")
        val goToMarket = Intent(Intent.ACTION_VIEW, uri)
        try {
            goToMarket.setClassName("com.tencent.android.qqdownloader", "com.tencent.pangu.link.LinkProxyActivity")
            context.startActivity(goToMarket)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
        }
    }

    //初使化app列表
    fun initList() {
        try {
            var sdCardExist = Environment.getExternalStorageState() == android.os.Environment.MEDIA_MOUNTED
            if (sdCardExist) {
                var text_file = File(Environment.getExternalStorageDirectory().path + "/apkpackagename.txt")
                if (text_file.exists()) {
                    var content = text_file.inputStream()
                    //读取push过来的包名
                    packageNamea = readTxtFile(content)
                    var packageNameSplit = packageNamea.split("|")
                    if (packageNameSplit[0] == "1") {
                        goToMarket(this, packageNameSplit[1])
                        finish()
                    } else {
                        myedit.setText("${packageNameSplit[1]}")
                    }
                } else {
                    Log.w("yy", "缺少配置文件>apkpackagename.txt")
                }
            }
        } catch (ex: Exception) {
            Log.w("yy", "配置文件出错" + ex.message)
            Toast.makeText(this, "配置文件出错", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    /**
     * 读TXT文件内容
     * @param filePath 文件路径(不要以 / 结尾)
     * @param fileName 文件名称（包含后缀,如：ReadMe.txt）
     * @return
     */
    fun readTxtFile(inputstream: InputStream): String {
        var bufferedReader: BufferedReader? = null
        val reader = InputStreamReader(inputstream)
        val sb=StringBuffer()
        try {
            bufferedReader = BufferedReader(reader)
            try {
                var read: String? = null
                while ({ read = bufferedReader!!.readLine();read }() != null) {
                    sb.append(read)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close()
            }
        }
        return sb.toString()
    }

    //正则匹配字符之间的内容
    fun getSubUtilSimple(soap: String, rgex: String): String {
        val pattern = Pattern.compile(rgex)// 匹配的模式
        val m = pattern.matcher(soap)
        while (m.find()) {
            return m.group(1)
        }
        return ""
    }

    fun setPermission() {
        //动态申请内存存储权限
        val rxPermissions = RxPermissions(this)
        rxPermissions.requestEach(
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe { permission ->
                    if (permission.granted) {
                        // 用户已经同意该权限
                        //android.permission.RECORD_AUDIO
                        Log.d("yy", permission.name + " is granted.")
                        if (permission.name == "android.permission.READ_EXTERNAL_STORAGE") {
                            setContentView(R.layout.activity_main)
                            initList()
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        Log.d("yy", permission.name + " is denied. More info should be provided.")
                        Toast.makeText(this@MainActivity, "请允许" + permission.name, Toast.LENGTH_SHORT).show()
                        System.exit(0)
                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        Log.d("yy", permission.name + " is denied.")
                        Toast.makeText(this@MainActivity, "请允许" + permission.name, Toast.LENGTH_SHORT).show()
                        System.exit(0)
                    }
                }

    }


}
